<template>
  <el-form ref="LoginFormRef" :model="formData" :rules="loginRules" class="login-el-form">
    <!--    用户名区域-->
    <el-form-item label="用户名" prop="username">
      <el-input v-model="formData.username" prefix-icon="el-icon-user"></el-input>
    </el-form-item>
    <!--    密码-->
    <el-form-item label="密码" prop="password">
      <el-input v-model="formData.password" prefix-icon="el-icon-lock"></el-input>
    </el-form-item>
    <!--按钮-->
    <el-form-item class="login-buttons">
      <el-button type="primary" v-on:click="okLogin">登录</el-button>
      <el-button type="info" @click="resetLoginForm">重置</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
export default {
  name: 'myLoginForm',
  data () {
    return {
      formData: {
        username: 'admin',
        password: 'admin'
      },
      // 表单数据验证规则对象
      loginRules: {
        // 验证用户名是否合法
        username: [
          {
            required: true,
            message: '请输入用户名',
            target: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '字数应该在2~10之间',
            target: 'blur'
          }
        ],
        // 验证密码是否合法
        password: [
          {
            required: true,
            message: '请输入密码',
            target: 'blur'
          },
          {
            min: 5,
            max: 15,
            message: '密码在5~15个字符之间',
            target: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 重置表单
    resetLoginForm () {
      this.$refs.LoginFormRef.resetFields()
      this.formData.username = ''
      this.formData.password = ''
    },
    okLogin () {
      this.$refs.LoginFormRef.validate(valid => {
        if (!valid) return
        this.$http.post('login', this.formData).then(resp => {
          if (resp.data.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: resp.data.meta.msg,
              duration: 1000,
              type: 'error'
            })
            this.$notify.error({
              title: '错误',
              message: resp.data.meta.msg,
              duration: 1000
            })
          } else {
            this.$message({
              showClose: true,
              message: '登录成功',
              duration: 1000,
              type: 'success'
            })
            // 登录成功后
            // 获取到token并保存到sessionStorage中
            // 除Login.vue之外的都必须携带token判断是否已经登录
            window.sessionStorage.setItem('token', resp.data.data.token)
            // 编程式导航跳转到后台页面,路由地址 /home
            this.$router.push('/home')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-el-form {
  padding: 30px 15px;

  .login-buttons {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
